package com.example.iread.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.iread.application.MyApplication;
import com.example.iread.bean.ResponseBean;
import com.example.iread.constant.ResponseCode;
import com.example.iread.exception.MyException;
import com.example.iread.exception.TokenExpireException;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


public final class HttpUtil {

    private static String token = "";

    private static final String NET_ERR_MSG = "Network Error";

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.SECONDS)
            .addInterceptor(chain -> {
                Request request = chain.request().newBuilder()
                        .addHeader("Authorization", "bearer " + token)
                        .build();
                return chain.proceed(request);
            })
            .addNetworkInterceptor(new StethoInterceptor())
            .build();

    private static final String baseUrl = "http://192.168.1.103:3007";
//    private static final String baseUrl = "http://192.168.10.108:3007";

    public static ResponseBean doGet(String url) {
        refreshToken();

        url = url.charAt(0) == '/' ? baseUrl + url : url;
        Request request = new Request.Builder().url(url).build();
        return getResponse(request);
    }

    public static ResponseBean doPost(String url) {
        return doPost(url, null);
    }

    public static ResponseBean doPost(String url, Map<String, String> body) {
        refreshToken();

        url = url.charAt(0) == '/' ? baseUrl + url : url;
        FormBody.Builder builder = new FormBody.Builder();
        if (body != null) {
            Set<Map.Entry<String, String>> entries = body.entrySet();
            entries.forEach(item -> builder.add(item.getKey(), item.getValue()));
        }
        FormBody formBody = builder.build();

        Request request = new Request.Builder().url(url).post(formBody).build();

        return getResponse(request);

    }

    private static void refreshToken() {
        SharedPreferences userInfo = MyApplication.getInstance().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = userInfo.getString("token", HttpUtil.token);
    }

    private static ResponseBean getResponse(Request request) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                ToastUtil.show(MyApplication.getInstance().getApplicationContext(), NET_ERR_MSG);
                throw new MyException(500, NET_ERR_MSG);
            }
            String resToString = responseBody.string();
            Log.i("SoRiya", "resToString: " + resToString);
            Gson gson = new Gson();
            ResponseBean responseBean = gson.fromJson(resToString, ResponseBean.class);
            int code = responseBean.code;
            String message = responseBean.message;

            if (code == ResponseCode.TOKEN_EXPIRE) {
                throw new TokenExpireException();
            } else if (code == ResponseCode.ERROR) {
                throw new MyException(code, message);
            }
            return responseBean;
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(500, NET_ERR_MSG);
        }
    }


    public static String getImageUrl(String path) {
        return baseUrl + path;
    }

}
